import { Form, Input, Button, Checkbox, message } from 'antd'

import { http, setToken } from '../../utils'

import './index.scss'

// 导入图片文件
import logo from '../../assets/images/logo.png'
import { useHistory, useLocation } from 'react-router-dom'

const Login = () => {
  const history = useHistory()
  const location = useLocation()

  const onFinish = async values => {
    const { code, mobile } = values

    try {
      const res = await http.post('/authorizations', {
        mobile,
        code
      })
      setToken(res.data.data.token)

      message.success('登录成功', 1, () => {
        if (location.state) {
          // 如果有值，就跳回到用户上一次访问的页面中
          history.push(location.state.from)
        } else {
          // 如果没有值，说明就是普通的直接登录，此时，就直接跳转到后台首页
          history.push('/home')
        }
      })
    } catch (error) {
      message.warning(error.response.data.message, 1)
    }
  }

  return (
    <div className="login">
      <div className="login-wrapper">
        <div>
          <img className="login-logo" src={logo} alt="" />
        </div>

        <Form
          className="login-form"
          initialValues={{
            remember: true,
            mobile: '13388886666',
            code: '246810'
          }}
          onFinish={onFinish}
          size="large"
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              {
                pattern: /^\d{6}$/,
                message: '请输入正确的验证码'
              }
            ]}
          >
            <Input placeholder="请输入验证码" maxLength={6} />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              block
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
